<template>
  <div class="container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>编辑宿舍楼</span>
          <el-button @click="goBack">返回列表</el-button>
        </div>
      </template>
      
      <el-form ref="formRef" :model="dorm" :rules="rules" label-width="120px" style="max-width: 600px;">
        <el-form-item label="宿舍楼ID" prop="dormBuildId">
          <el-input v-model="dorm.dormBuildId" disabled />
        </el-form-item>
        
        <el-form-item label="宿舍楼名称" prop="dormBuildName">
          <el-input v-model="dorm.dormBuildName" placeholder="请输入宿舍楼名称" />
        </el-form-item>
        
        <el-form-item label="管理员" prop="dormBuildUser">
          <el-select 
            v-model="dorm.dormBuildUser" 
            filterable
            placeholder="请选择管理员"
            style="width: 100%"
          >
            <el-option
              v-for="user in users"
              :key="user.id"
              :label="user.userName"
              :value="user.userName"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios'
import { ElMessage } from 'element-plus'

export default {
  data() {
    return {
      dorm: {
        dormBuildId: null,
        dormBuildName: '',
        dormBuildUser: ''
      },
      users: [],
      rules: {
        dormBuildName: [
          { required: true, message: '请输入宿舍楼名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        dormBuildUser: [
          { required: true, message: '请选择管理员', trigger: 'change' }
        ]
      }
    }
  },
  async created() {
    await Promise.all([this.fetchDorm(), this.fetchUsers()])
  },
  methods: {
    async fetchDorm() {
      try {
        const dormId = this.$route.params.id
        const response = await axios.get(
          `http://localhost:8080/UserMgr_Web_exploded/dorms/${dormId}`,
          {
            headers: {
              'Authorization': 'Bearer ' + localStorage.getItem('token')
            }
          }
        )
        this.dorm = response.data
      } catch (error) {
        ElMessage.error('获取宿舍楼信息失败')
        console.error(error)
      }
    },
    async fetchUsers() {
      try {
        const response = await axios.get(
          "http://localhost:8080/UserMgr_Web_exploded/users",
          {
            headers: {
              'Authorization': 'Bearer ' + localStorage.getItem('token')
            }
          }
        )
        this.users = response.data
      } catch (error) {
        ElMessage.error('获取用户列表失败')
        console.error(error)
      }
    },
    async submitForm() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            const response = await axios.put(
              `http://localhost:8080/UserMgr_Web_exploded/dorms/${this.dorm.dormBuildId}`,
              this.dorm,
              {
                headers: {
                  'Authorization': 'Bearer ' + localStorage.getItem('token')
                }
              }
            )
            
            if (response.data.success) {
              ElMessage.success('更新宿舍楼成功')
              this.$router.push('/dorms')
            } else {
              ElMessage.error(response.data.message || '更新失败')
            }
          } catch (error) {
            ElMessage.error('更新宿舍楼失败')
            console.error(error)
          }
        }
      })
    },
    goBack() {
      this.$router.push('/dorms')
    }
  }
}
</script>